import { Form, Button, Input, Table, Modal, Popover, Select, Card, Pagination } from 'antd'
import React, { useState, useEffect } from 'react'
import CustomBreadcrumb from '@/components/CustomBreadcrumb'
import { useRequest } from 'ahooks'
import { withRouter } from 'react-router-dom'
import { requestWrapper } from '@/utils/request'
import userAPI from '@/services/user'
import iacFormat from '@/utils/format'
import './styles.scss'
const { confirm } = Modal
const { Search } = Input
const { Option } = Select

const EditPopover = ({ type, getFieldDecorator, children, submit, userId }) => {
    const [visible, setVisible] = useState(false)
    const [loading, setLoading] = useState(false)
    return (
        <Popover
            placement='left'
            visible={visible}
            onVisibleChange={visible => setVisible(visible)}
            content={
                <div className='role_form'>
                    <h4>{type === 'role' ? '修改权限' : '修改密码'}</h4>
                    <Form
                        onSubmit={() => {
                            submit(userId)
                            setLoading(true)
                            setTimeout(() => {
                                setLoading(false)
                                setVisible(false)
                            }, 1000)
                        }}>
                        <Form.Item>
                            {type === 'role'
                                ? getFieldDecorator('role', {})(
                                      <Select style={{ width: 120 }}>
                                          <Option value='admin'>管理员</Option>
                                          <Option value='normal'>普通用户</Option>
                                      </Select>
                                  )
                                : getFieldDecorator('password', {
                                      rules: [
                                          {
                                              pattern: new RegExp('^[0-9a-zA-Z_]{1,}$', 'g'),
                                              message: '只允许包含数字、字母、下划线'
                                          },
                                          { min: 6, message: '密码不得少于6位' },
                                          { max: 16, message: '密码不能超过16位' }
                                      ]
                                  })(<Input type='password' placeholder='新密码' />)}
                            {type === 'role' ? (
                                <Button
                                    type='primary'
                                    htmlType='submit'
                                    style={{ marginLeft: '20px' }}
                                    loading={loading}>
                                    确认
                                </Button>
                            ) : (
                                <Button
                                    type='primary'
                                    htmlType='submit'
                                    style={{ marginTop: '20px', float: 'right' }}
                                    loading={loading}>
                                    确认
                                </Button>
                            )}
                        </Form.Item>
                    </Form>
                </div>
            }
            trigger='click'
            destroyTooltipOnHide={true}
            visible={visible}
            onVisibleChange={visible => setVisible(visible)}>
            {children}
        </Popover>
    )
}

const App = props => {
    const [showData, setShowData] = useState([])
    const [delKeys, setDelKeys] = useState([])
    const [visible, setVisible] = useState(false)
    const [keyword, setKeyword] = useState('')
    const { getFieldDecorator } = props.form

    const [me, setMe] = useState({})

    const { data: userList, run: getUserList, refresh } = useRequest(
        ({ page }) => requestWrapper(userAPI.list.bind(null, { q: keyword, page: page, pageSize: 10 })),
        {
            formatResult: data => data || [],
            defaultParams: [{ page: 1 }],
            onSuccess: () => {
                const tempList = userList.list.map(val => {
                    val.createTime = iacFormat(val.createTime)
                    return val
                })
                setShowData(tempList)
            }
        }
    )

    const { data, run: deletes, loading: delLoading } = useRequest(
        ids =>
            requestWrapper(userAPI.deletes.bind(null, { userIds: ids }), {
                autoSuccess: true,
                errorMessage: '只有管理员才能删除其它用户！'
            }),
        {
            manual: true,
            onSuccess: () => {
                refresh()
                setVisible(false)
                setDelKeys([])
            }
        }
    )

    const { run: adminUpdateUser, loading: updateLoading } = useRequest(
        ({ id, params }) =>
            requestWrapper(userAPI.adminUpdateUser.bind(null, id, params), {
                autoSuccess: true,
                errorMessage: '只有管理员才能修改他人信息！'
            }),
        {
            manual: true,
            onSuccess: () => {
                refresh()
            }
        }
    )

    const { run: deleteUser, loading: delUserLoading } = useRequest(
        id =>
            requestWrapper(userAPI.delete.bind(null, id), {
                autoSuccess: true,
                errorMessage: '只有管理员才能删除其它用户！'
            }),
        {
            manual: true,
            onSuccess: () => {
                refresh()
                setVisible(false)
                setDelKeys([])
            }
        }
    )

    const submit = id => {
        props.form.validateFields((err, values) => {
            if (!err) {
                if (values.role !== undefined || values.password !== undefined) {
                    console.log(1231)
                    adminUpdateUser({ id: id, params: values })
                } else {
                    return
                }
            }
        })
    }

    const columns = [
        {
            width: 200,
            title: '创建时间',
            dataIndex: 'createTime'
        },
        {
            width: 200,
            title: '姓名',
            dataIndex: 'username'
        },
        {
            width: 60,
            title: '年龄',
            dataIndex: 'age'
        },
        {
            width: 80,
            title: '权限',
            dataIndex: 'role',
            render: (text, record) => {
                return record.role === 'admin' ? (
                    <span className='role'>管理员 </span>
                ) : (
                    <span className='role'>普通用户 </span>
                )
            },
            filters: [
                {
                    text: '普通用户',
                    value: 'normal'
                },
                {
                    text: '管理员',
                    value: 'admin'
                }
            ],
            onFilter: (value, record) => record.role.indexOf(value) === 0
        },
        {
            width: 270,
            title: '操作',
            render: (text, record) => (
                <span>
                    <EditPopover
                        userId={record.id}
                        type='role'
                        getFieldDecorator={getFieldDecorator}
                        submit={submit}
                        children={<a>修改权限</a>}></EditPopover>
                    <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    <EditPopover
                        userId={record.id}
                        type='password'
                        getFieldDecorator={getFieldDecorator}
                        submit={submit}
                        children={<a className='updatePass'>修改密码</a>}></EditPopover>
                    <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    <a className='del' onClick={() => confirmDel(record)}>
                        删除用户
                    </a>
                </span>
            )
        }
    ]

    const confirmDel = record => {
        confirm({
            title: '你确定要删除该用户吗?',
            content: '当你删除该用户之后，该用户的作品将删除！',
            okText: '确定删除',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                return new Promise((resolve, reject) => {
                    setTimeout(() => {
                        deleteUser(record.id)
                        resolve()
                    }, 1500)
                })
            },
            onCancel() {}
        })
    }

    const del = () => {
        if (delKeys.length > 0) {
            setVisible(true)
        } else {
            Modal.info({
                title: '您还没有选择要删除的人用户！',
                onOk() {}
            })
        }
    }

    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            // var temp = this.state.delKeys
            setDelKeys(`${selectedRowKeys}` === '' ? [] : `${selectedRowKeys}`.split(','))
            console.log(delKeys)
            // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        },
        getCheckboxProps: record => ({
            disabled: record.name === 'Disabled User',
            // Column configuration not to be checked
            name: record.name
        })
    }

    const search = q => {}

    const cardTitle = () => {
        return (
            <div>
                <span className='title'>用户列表</span>
                <Search
                    className='list_search'
                    placeholder='input search text'
                    onChange={v => {
                        setKeyword(v.target.value)
                    }}
                    onSearch={() => getUserList({ page: 1 })}
                    style={{ width: 600 }}
                />
            </div>
        )
    }

    return (
        <div className='user_list' style={{ minWidth: '1200px' }}>
            <div>
                <CustomBreadcrumb arr={['用户管理', '用户列表']}></CustomBreadcrumb>
            </div>
            <Modal
                title='警告'
                visible={visible}
                onOk={() => deletes(delKeys)}
                confirmLoading={delLoading}
                onCancel={() => setVisible(false)}
                okText='确认删除'
                cancelText='取消'
                okButtonProps={{ type: 'danger', value: '确认删除' }}>
                <h4>你确定要删除用户吗?</h4>
            </Modal>
            <span>
                <Button onClick={del} type='danger'>
                    批量删除
                </Button>
            </span>
            <Card type='inner' title={cardTitle()} className='card'>
                <Table
                    pagination={false}
                    className='list_table'
                    rowSelection={rowSelection}
                    dataSource={showData}
                    columns={columns}
                    rowKey={items => items.id}></Table>
            </Card>
            <Pagination
                // hideOnSinglePage={true}
                defaultCurrent={1}
                pageSize={10}
                total={userList && userList.total}
                onChange={v => {
                    getUserList({ page: v })
                }}
            />
        </div>
    )
}

export default withRouter(Form.create()(App))
